package com.springcloud.gateway.filter;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.omg.CORBA.ServerRequest;
import org.springframework.boot.actuate.autoconfigure.endpoint.web.WebEndpointProperties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.util.UriComponentsBuilder;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0
 * @Author 宋聚智
 * @Date 2019/11/1 14:43
 * @description
 * @Modify By：
 * @ModifyTime： 2019/11/1
 * @Modify marker：
 **/

@Slf4j
@Configuration
@RequiredArgsConstructor
@ConditionalOnProperty(value="blade.log.request.enabled",havingValue = "true",matchIfMissing = true)
public class GlobalResponseLogFilter implements GlobalFilter, Ordered {
    private final WebEndpointProperties endpointProperties;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request =exchange.getRequest();
        String path = request.getPath().pathWithinApplication().value();
        String endpointBasePath = endpointProperties.getBasePath();
        //忽略endpoint
        if(StringUtils.isNotBlank(endpointBasePath)&& path.startsWith(endpointBasePath)){
            return chain.filter(exchange);
        }

        return chain.filter(exchange).then(
                Mono.fromRunnable(()->{
                    MultiValueMap<String,String> queryParam= request.getQueryParams();
                    String requestUrl= UriComponentsBuilder.fromPath(path).queryParams(queryParam).build().toUriString();
                    StringBuffer responseLog= new StringBuffer(300);
                    List<Object> responseArgs= new ArrayList<>();

                    responseLog.append("\n\n=========== Gateway Response Start========\n");
                    ServerHttpResponse response =exchange.getResponse();
                    responseLog.append("<===={},{}:{}\n");
                    String requestMethod= request.getMethodValue();
                    responseArgs.add(response.getStatusCode().value());
                    responseArgs.add(requestMethod);
                    responseArgs.add(requestUrl);

                    HttpHeaders headers = response.getHeaders();
                    headers.forEach((headerName,headerValue)->{
                        responseLog.append("===Headers==={}:{}\n");
                        responseArgs.add(headerName);
                        responseArgs.add(StringUtils.join(headerValue));
                    });

                    responseLog.append("==============Gateway Response End =================");
                    log.info(responseLog.toString(),responseArgs.toArray());

                })
        );
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}
